from alipay import AliPay
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse

from AXF.settings import PUBLIC_KEY, PRIVATE_KEY
from CartApp.models import AxfCart
from CartApp.view_helper import get_total_price
from OrderApp.models import AxfOrder, OrderGoods


def makeOrder(request):
    user_id = request.session.get('user_id')
    # 总价
    price = get_total_price(user_id)
    # 创建订单对象
    order = AxfOrder()
    order.o_user_id = user_id
    order.o_price = price

    order.save()

    # orderaddress
    # 当前用户在购物车中所有选中的商品
    carts = AxfCart.objects.filter(c_user_id=user_id).filter(c_is_select=True)
    # 一个购物车对象，对应一个订单商品
    for cart in carts:
        # 将购物车中选择的商品全部添加到订单表中
        ordergoods = OrderGoods()
        ordergoods.o_order = order
        ordergoods.o_goods = cart.c_goods
        ordergoods.o_goods_num = cart.c_goods_num

        ordergoods.save()

        # 此时订单商品表中已经有了数据，接下来要删除购物车的数据
        cart.delete()

    data = {
        'msg': 'ok',
        'status': 200,
        'order_id': order.id,
    }

    return JsonResponse(data=data)


def orderDetail(request):
    order_id = request.GET.get('order_id')

    order = AxfOrder.objects.get(pk=order_id)

    context = {
        'order': order,
    }

    return render(request, 'AXF/order/order_detail.html', context=context)


# 调用支付宝接口
def testpay(request):
    alipay = AliPay(
        appid="2021000116667058",
        app_notify_url=None,  # 默认回调url
        app_private_key_string=PRIVATE_KEY,
        # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
        alipay_public_key_string=PUBLIC_KEY,
        sign_type="RSA2",  # RSA 或者 RSA2
        debug=False,  # 默认False
        # config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
    )

    subject = "华为p40pro"   # 测试订单

    # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string   # 支付宝网关已经改了，GitHub中没有该
    order_string = alipay.api_alipay_trade_page_pay(
        out_trade_no="20161112",
        total_amount=100,
        subject=subject,
        return_url="https://example.com",
        notify_url="https://example.com/notify"  # 可选, 不填则使用默认notify url
    )

    # 支付宝网关： https: // openapi.alipaydev.com / gateway.do
    return redirect('https://openapi.alipaydev.com/gateway.do?'+order_string)

# http://127.0.0.1:8000/axforder/testpay/